package com.voicechat.firstmet.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGADynamicEntity;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.adapter.CommunityAdapter;
import com.voicechat.firstmet.adapter.GifAdapter;
import com.voicechat.firstmet.adapter.MsgGifGridViewAdapter;
import com.voicechat.firstmet.adapter.PictureAdapter;
import com.voicechat.firstmet.adapter.ViewPagerAdapter;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.CharmBean;
import com.voicechat.firstmet.bean.CommBean;
import com.voicechat.firstmet.bean.CoummunityNotice;
import com.voicechat.firstmet.bean.GifBean;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PhotoAlbumBean;
import com.voicechat.firstmet.bean.PostBean;
import com.voicechat.firstmet.bean.VoiceAppraiseBean;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.client.WsManager;
import com.voicechat.firstmet.dialog.AlertDialog;
import com.voicechat.firstmet.imcontrol.MediaUtil;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.CommunityService;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.net.service.PersonDataService;
import com.voicechat.firstmet.realm.ListBean;
import com.voicechat.firstmet.utils.CheckAudioPermission;
import com.voicechat.firstmet.utils.ConstantSet;
import com.voicechat.firstmet.utils.DisplayUtil;
import com.voicechat.firstmet.utils.FileUtils;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.RealmUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.utils.ThreadManager;
import com.voicechat.firstmet.utils.Utils;
import com.voicechat.firstmet.view.CirclePageIndicator;
import com.voicechat.firstmet.view.CustomLinearLayoutManager;
import com.voicechat.firstmet.view.LabelsView;
import com.voicechat.firstmet.view.MyScrollView;
import com.voicechat.firstmet.view.ShadowDrawable;

import org.jetbrains.annotations.NotNull;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: PersonalHomepageActivity
 * @Description: 个人主页
 * @Author: ljp
 * @CreateDate: 2018/9/7 16:50
 * @Version: 1.0
 */
public class PersonalHomepageActivity extends BaseActivity {
    @BindView(R.id.image_icon_backgroud)
    ImageView imageIconBackgroud;
    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.tv_nike_name)
    TextView tvNikeName;
    @BindView(R.id.image_sex)
    ImageView imageSex;
    @BindView(R.id.tv_age)
    TextView tvAge;
    @BindView(R.id.image_vip)
    ImageView imageVip;
    @BindView(R.id.tv_intro)
    TextView tvIntro;
    /* @BindView(R.id.voice_time)
     TextView voiceTime;*/
    @BindView(R.id.linear_voice)
    LinearLayout linearVoice;
    @BindView(R.id.tv_user_id)
    TextView tvUserId;
    @BindView(R.id.tv_fans)
    TextView tvFans;
    @BindView(R.id.tv_concern)
    TextView tvConcern;
    @BindView(R.id.linear_my_photo)
    LinearLayout linearMyPhoto;
    @BindView(R.id.recy_photo)
    RecyclerView recyPhoto;
    //@BindView(R.id.tv_call_rate)
    // TextView tvCallRate;
    //@BindView(R.id.tv_call_number)
    // TextView tvCallNumber;
    // @BindView(R.id.rating_bar)
    // RatingBarViewShow ratingBar;
    // @BindView(R.id.tv_scores)
    // TextView tvScores;
    @BindView(R.id.largeLabel)
    LabelsView largeLabel;
    /* @BindView(R.id.largeLabe2)
            LabelsView largeLabe2;*/
    @BindView(R.id.linear_my_gif)
    LinearLayout linearMyGif;
    @BindView(R.id.recy_gif)
    RecyclerView recyGif;
    @BindView(R.id.linear_dynamic_state)
    LinearLayout linearDynamicState;
    @BindView(R.id.recy_dynamic_state)
    RecyclerView recyDynamicState;
    /*@BindView(R.id.linear_white)
    LinearLayout linearWhite;*/
    @BindView(R.id.image_share_tr)
    ImageView imageShareTr;
    @BindView(R.id.image_more_tr)
    ImageView imageMoreTr;
    @BindView(R.id.linear_transparency)
    LinearLayout linearTransparency;
    @BindView(R.id.tv_attention)
    TextView tvAttention;
    @BindView(R.id.scroll_view)
    MyScrollView scrollView;
    @BindView(R.id.linear_over)
    LinearLayout linearOver;
    @BindView(R.id.linear_back_age)
    LinearLayout linearBackAge;
    @BindView(R.id.image_is_anchor)
    ImageView imageIsAnchor;
    @BindView(R.id.tv_anchor_text)
    TextView tvAnchorText;
    //@BindView(R.id.tv_line_state)
    // TextView tvLineState;
    @BindView(R.id.linear_accost)
    LinearLayout linearAccost;
    @BindView(R.id.linear_gif)
    LinearLayout linearGif;
    @BindView(R.id.linear_chat)
    LinearLayout linearChat;
    @BindView(R.id.image_voice)
    ImageView imageVoice;
    @BindView(R.id.svgImage)
    SVGAImageView svgImage;
    @BindView(R.id.view_photo)
    View viewPhoto;
    @BindView(R.id.view_gift)
    View viewGift;
     /*@BindView(R.id.view_dynamic)
     View viewDynamic;*/
    @BindView(R.id.image_is_real)
    ImageView imageIsReal;
    @BindView(R.id.image_attention)
    ImageView imageAttention;
    @BindView(R.id.linear_attention)
    LinearLayout linearAttention;
    @BindView(R.id.image_anchor)
    ImageView imageAnchor;
    @BindView(R.id.linear_labor_union)
    LinearLayout linearLaborUnion;
    @BindView(R.id.linear_add_friends)
    LinearLayout linearAddFriends;
    @BindView(R.id.image_add)
    ImageView imageAdd;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    @BindView(R.id.tv_data)
    TextView tvData;
    @BindView(R.id.linear_label)
    LinearLayout linearLabel;
    @BindView(R.id.view_label)
    View viewLabel;

    /* @BindView(R.id.image_back2)
     ImageView imageBack2;*/
    private String TAG = "PersonalHomepageActivity";
    private boolean isGone = true;
    private int mAlpha;
    private String anchorId;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String token;
    private String id;
    private String deviceInfo;
    ArrayList<String> labelData;//个人资料label
    ArrayList<String> labeVoice;//语聊
    PictureAdapter pictureAdapter;
    List<PhotoAlbumBean.PageBean.ListBean> listImages;
    GifAdapter gifAdapter;
    List<GifBean.PageBean.ListBean> gifBeans;
    private int page;
    private StringBuffer sbData;//资料信息
    private CommunityAdapter communityAdapter;
    private List<PostBean.PageBean.ListBean> postLists;
    private MySelfInfoBean.ObjectBean objectBean;
    private CharmBean.ObjectBean charmBeanObject;
    private Runnable runnable;
    private MediaUtil mediaUtil;
    private AnimationDrawable frameAnimatio;
    private String voicePath;
    private AlertDialog myDialog;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_person_home;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        anchorId = getIntent().getStringExtra("anchorId");//对方的id
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        id = mySeleInfo.getId();
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        //setContentView(scrollView);\
        myDialog = new AlertDialog(context).builder();
        initView();
    }

    public static void navToChat(Context context, String otherId) {
        Intent intent = new Intent(context, PersonalHomepageActivity.class);
        intent.putExtra("anchorId", otherId);
        context.startActivity(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    /**
     * @return
     * @method
     * @description 数据实例化
     * @date: 2018/10/29 10:48
     * @author: ljp
     */
    private void initView() {
        sbData = new StringBuffer();
        ShadowDrawable.setShadowDrawable(linearOver,
                Color.parseColor("#ffffff"),
                DisplayUtil.dp2px(context, 14),
                Color.parseColor("#1a2f28ae"), DisplayUtil.dp2px(context, 9), 0, 3);
        // Log.i(TAG, "initView: ---anchorId--" + anchorId);
        if (anchorId.equals(mySeleInfo.getId())) {//如果是自己不显示关注按钮和举报按钮
            linearAttention.setVisibility(View.GONE);
            imageMoreTr.setVisibility(View.GONE);
            linearChat.setVisibility(View.GONE);
            linearAddFriends.setVisibility(View.GONE);
        }
        page = 1;
        labelData = new ArrayList<>();
        //   ratingBar.setClickable(false);
        //ratingBar.setStar(4, false, this);
        labeVoice = new ArrayList<>();
        listImages = new ArrayList<>();
        gifBeans = new ArrayList<>();
        postLists = new ArrayList<>();
        pictureAdapter = new PictureAdapter(context, listImages, R.layout.item_picure_photo, "home");
        CustomLinearLayoutManager linearLayoutManager = new CustomLinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false, false);
        recyPhoto.setLayoutManager(linearLayoutManager);
        recyPhoto.setAdapter(pictureAdapter);
        gifAdapter = new GifAdapter(context, gifBeans, R.layout.item_gif);
        recyGif.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        recyGif.setAdapter(gifAdapter);
        communityAdapter = new CommunityAdapter(context, postLists, R.layout.item1_community, "person");
        recyDynamicState.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyDynamicState.setAdapter(communityAdapter);
        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        scrollView.setScrollViewListener(new MyScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(View scrollView, int x, int y, int oldx, int oldy) {
                int minHeight = 50;
                int maxHeight = imageIconBackgroud.getMeasuredHeight();
                if (maxHeight == 0) {
                    maxHeight = 500;
                }
                if (scrollView.getScrollY() <= minHeight) {
                    mAlpha = 0;
                } else if (scrollView.getScrollY() > maxHeight) {
                    mAlpha = 255;
                } else {
                    mAlpha = (scrollView.getScrollY() - minHeight) * 255 / (maxHeight - minHeight);
                }
                if (mAlpha <= 0) {
                    //tv_title.setTextColor(Color.rgb(255, 255, 255));
                    iconColorFilter(Color.parseColor("#ffffff"));
                    linearTransparency.setBackgroundColor(Color.argb(0, 255, 255, 255));
                    tvAdd.setTextColor(Color.parseColor("#ffffff"));
                } else if (mAlpha >= 255) {
                    // tv_title.setTextColor(Color.rgb(0, 0, 0));
                    iconColorFilter(Color.parseColor("#000000"));
                    linearTransparency.setBackgroundColor(Color.argb(mAlpha, 255, 255, 255));
                    tvAdd.setTextColor(Color.parseColor("#000000"));

                } else {
                    //tv_title.setTextColor(Color.rgb(255 - mAlpha, 255 - mAlpha, 255 - mAlpha));
                    iconColorFilter(Color.rgb(255 - mAlpha, 255 - mAlpha, 255 - mAlpha));
                    linearTransparency.setBackgroundColor(Color.argb(mAlpha, mAlpha, mAlpha, mAlpha));
                    tvAdd.setTextColor((Color.rgb(255 - mAlpha, 255 - mAlpha, 255 - mAlpha)));
                }
            }
        });
        getHttp();
        communityAdapter.setItemSetClick(new CommunityAdapter.ItemSetClick() {

            @Override
            public void setIconClick(View view, PostBean.PageBean.ListBean listBean) {

            }

            @Override
            public void setIconClick(View view, CommBean.MapBean.DynamicBean dynamic) {

            }

            @Override
            public void setItemClick(View view, PostBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(context, PostDetailsActivity.class);
                intent.putExtra("listBean", listBean);
                startActivity(intent);
            }

            @Override
            public void setLikeClick(View view, CommBean.MapBean.DynamicBean dynamic) {
            }

            @Override
            public void setLikeClick(View view, PostBean.PageBean.ListBean listBean) {
                CommunityService.postLikeAndUnLike(token, deviceInfo, listBean.getId(),
                        CommunityService.LIKE_TYPE.LIKE_POST_TYPE, mySeleInfo.getId()).subscribe(result -> {
                    if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                        if (listBean.getIsFabulous().equals("0")) {//0未点赞 1 点赞
                            listBean.setIsFabulous("1");
                            listBean.setFabulousCount(listBean.getFabulousCount() + 1);
                        } else if (listBean.getIsFabulous().equals("1")) {
                            listBean.setIsFabulous("0");
                            listBean.setFabulousCount(listBean.getFabulousCount() - 1);
                        }
                        communityAdapter.notifyDataSetChanged();
                    } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                        Utils.setToken(context);
                    } else {
                        toast_MakeText(result.getMsg());
                    }
                    // Log.i(TAG, "setLikeClick: -------"+result.toString());
                }, throwable -> {
                    // Log.i(TAG, "setLikeClick: -------"+throwable.toString());
                });
            }

            @Override
            public void setItemClick(View view, CommBean.MapBean.DynamicBean dynamic) {
            }

            @Override
            public void setNoticeClick(View view, List<CoummunityNotice.PageBean.ListBean> notices) {
            }

            @Override
            public void setPlayVoiceClick(PostBean.PageBean.ListBean listBean, View view, int position, View imagePlay) {
                String path = ConstantSet.VOICEINTR + ConstantSet.VOICE_POST + Utils.getVoiceName(listBean.getVoiceUrl());
                Log.i(TAG, "onBindViewHolder: -----" + path);
                if (FileUtils.isExists(path)) {
                    try {
                        player(path, (ImageView) view, position,(ImageView) imagePlay);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void setPlayVoiceClick(CommBean.MapBean.DynamicBean dynamic, View view, int position) {
            }

            @Override
            public void setItemClickShare(View view, PostBean.PageBean.ListBean listBean) {
                UMWeb web = new UMWeb(HTTPAPI.URL_SHARE + "id=" + listBean.getId() + "&userId=" + listBean.getUserId());
                String[] list = getResources().getStringArray(R.array.share_title);
                Random random = new Random();
                web.setTitle(list[random.nextInt(list.length)]);//标题
                if (!TextUtils.isEmpty(listBean.getUrl())) {
                    String[] strings = Utils.spitPictureUrl(listBean.getUrl());
                    web.setThumb(new UMImage(activity, OssConfig.OSS_HTTP + strings[0]));  //缩略图
                }
                web.setDescription(listBean.getContent());//描述
                new ShareAction(activity).withMedia(web)
                        .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(new UMShareListener() {
                            @Override
                            public void onStart(SHARE_MEDIA share_media) {
                            }

                            @Override
                            public void onResult(SHARE_MEDIA share_media) {
                                Toast.makeText(activity, getResources().getString(R.string.share_success), Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                Toast.makeText(activity, getResources().getString(R.string.share_fial), Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void onCancel(SHARE_MEDIA share_media) {
                                Toast.makeText(activity, getResources().getString(R.string.share_cacal), Toast.LENGTH_LONG).show();
                            }
                        }).open();
            }
        });
        pictureAdapter.setOnClick(new PictureAdapter.OnClick() {
            @Override
            public void onSetPictureClick(View view, int position) {
                if (mySeleInfo.getvType().equals("0")) {
                    toast_MakeText(getResources().getString(R.string.vip_text));
                }else {
                    Intent intent1 = new Intent(activity, PhotoAlbumActivity.class);
                    intent1.putExtra("anchorId", anchorId);
                    startActivity(intent1);
                }
            }
        });
        linearAttention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (charmBeanObject != null) {
                    setHttpLike();
                }
            }
        });
    }

    int mFirstVoicePlayItem;//第一级列表的喇叭动画初始位置
    int mSecondVoicePlayItem;//第二级列表的喇叭动画初始位置
    //int position;//当前列表的位置
    AnimationDrawable animationDrawable;

    /**
     * @return
     * @method
     * @description 播放语音
     * @date: 2018/9/28 18:57
     * @author: ljp
     */
    private void player(String path, ImageView imageView, int position,ImageView imagePlay) throws FileNotFoundException {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        mSecondVoicePlayItem = -1;
        if (animationDrawable != null) {
            imagePlay.setImageResource(R.mipmap.post_pause);
            MediaUtil.getInstance().stop();
            animationDrawable.stop();
            animationDrawable.selectDrawable(2);
            animationDrawable = null;
            if (mFirstVoicePlayItem != position) {
                mFirstVoicePlayItem = position;
                imageView.setImageResource(R.drawable.post_voice);
                animationDrawable = (AnimationDrawable) imageView.getDrawable();
                animationDrawable.start();
                MediaUtil.getInstance().play(new FileInputStream(path));
                imagePlay.setImageResource(R.mipmap.post_play);
            }
        } else {
            mFirstVoicePlayItem = position;
            imageView.setImageResource(R.drawable.post_voice);
            animationDrawable = (AnimationDrawable) imageView.getDrawable();
            animationDrawable.start();
            MediaUtil.getInstance().play(new FileInputStream(path));
            imagePlay.setImageResource(R.mipmap.post_play);
        }
        MediaUtil.getInstance().setEventListener(new MediaUtil.EventListener() {
            @Override
            public void onStop() {
                imagePlay.setImageResource(R.mipmap.post_pause);
            }
        });
        MediaUtil.getInstance().getPlayer().setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                imagePlay.setImageResource(R.mipmap.post_pause);
                if (animationDrawable != null) {
                    animationDrawable.stop();
                    animationDrawable.selectDrawable(2);
                    animationDrawable = null;
                }
            }
        });
    }

    /**
     * @return
     * @method
     * @description 启动线程池下载语音信息
     * @date: 2018/10/16 14:30
     * @author: ljp
     */
    private void setThreadPost(List<PostBean.PageBean.ListBean> postBeans) {
        ThreadManager.getThreadPool().execute(runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < postBeans.size(); i++) {
                    if (!TextUtils.isEmpty(postBeans.get(i).getVoiceUrl())) {
                        String voiceInfo = postBeans.get(i).getVoiceUrl();
                        int finalI = i;
                        OssClient.getInstance().init(context).fileDownload(voiceInfo, new OssClient.OnDownloadFile() {
                            @Override
                            public void onDownFileSuccess(InputStream inputStream) {
                                String voiceName = Utils.getVoiceName(postBeans.get(finalI).getVoiceUrl());
                                //Log.i(TAG, "onDownFileSuccess: ---------"+voiceName);
                                String path = ConstantSet.VOICEINTR;
                                try {
                                    OssConfig.writeToLocalPost(path, inputStream, voiceName);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onDownFileProgress(String progress) {
                                //Log.i(TAG, "onDownFileProgress: ----------"+progress);
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * @return
     * @method
     * @description 关注取消关注
     * @date: 2018/10/24 11:56
     * @author: ljp
     */
    private void setHttpLike() {
        MeInfoService.likeAndUnLike(token, deviceInfo, mySeleInfo.getId(), anchorId).subscribe(result -> {
            Log.i(TAG, "setHttpLike: --------" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                if (charmBeanObject.getState() == 1) {//1 未关注 2已经关注 3互相关注
                    imageAttention.setImageResource(0);
                    tvAttention.setText("已关注");
                    linearAttention.setBackgroundResource(R.drawable.btn_layout_red);
                    charmBeanObject.setState(2);
                } else if (charmBeanObject.getState() == 2) {
                    imageAttention.setImageResource(R.mipmap.person_flow);
                    tvAttention.setText("关注");
                    linearAttention.setBackgroundResource(R.drawable.btn_layout_red);
                    charmBeanObject.setState(1);
                } else if (charmBeanObject.getState() == 3) {
                    imageAttention.setImageResource(R.mipmap.person_flow);
                    tvAttention.setText("关注");
                    linearAttention.setBackgroundResource(R.drawable.btn_layout_red);
                    charmBeanObject.setState(1);
                }
                //toast_MakeText(result.getMsg());
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                removeAllActivity();
                startActivity(new Intent(activity, LoginActivity.class));
            } else {
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "setHttpLike: ------" + throwable.toString());

        });

    }

    /**
     * @return
     * @method
     * @description 更多popu
     * @date: 2018/9/11 19:50
     * @author: ljp
     */
    private void showPopu(View view) {
        View view1 = View.inflate(context, R.layout.popu_person_data, null);
        //PopUtils.showDown(activity_imessage,view,view1, -1,-1);
        int location[] = new int[2];
        view.getLocationOnScreen(location);
        int x = location[0];
        PopUtils.showPopupWindow(view1, view, activity, true, Gravity.NO_GRAVITY,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                -(int) getResources().getDimension(R.dimen.x250), 0, 1.0f);
        TextView tvReport = view1.findViewById(R.id.tv_report);//举报
        TextView tvComplain = view1.findViewById(R.id.tv_complain);//投诉
        tvComplain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, ComplainActivity.class);
                intent.putExtra("otherId", anchorId);
                startActivity(intent);
                PopUtils.hidePopupWindow();
            }
        });
        tvReport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, ReportActivity.class);
                intent.putExtra("otherId", anchorId);
                startActivity(intent);
                PopUtils.hidePopupWindow();
            }
        });
    }

    /**
     * @return
     * @method
     * @description 各种网络请求
     * @date: 2018/10/29 10:48
     * @author: ljp
     */
    private void getHttp() {
        setHomeHeard();
        setHomeState();
        showPersonVoice();
        setHomePhoto();
        setHomeGif();
        showPersonPosts();
    }

    /**
     * @return
     * @method
     * @description 请求头信息
     * @date: 2018/10/26 17:33
     * @author: ljp
     */
    private void setHomeHeard() {
        PersonDataService.showPersonHome(token, deviceInfo, id, anchorId, mySeleInfo.getVagrancy() + "").subscribe(personDataBean -> {
            Log.i(TAG, "setHomeHeard: ----" + personDataBean.getObject().toString());
            if (personDataBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                objectBean = personDataBean.getObject();
                setHeardData(personDataBean.getObject());
                if (!TextUtils.isEmpty(personDataBean.getObject().getVoiceInfo())) {
                    setThread(personDataBean.getObject().getVoiceInfo());
                }
            } else if (personDataBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(personDataBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "setHomeHeard: -----" + throwable.toString());

        });
    }
    /**
     * @return
     * @method
     * @description 设置头部数据
     * @date: 2018/10/29 9:38
     * @author: ljp
     */
    private void setHeardData(MySelfInfoBean.ObjectBean object) {
        objectBean = object;
        Log.i(TAG, "setHeardData: -----" + object.toString());
        GlideLoadUtils.getInstance().glideLoad(context, OssConfig.OSS_HTTP + object.getAvatarUrl(),
                imageIconBackgroud);
        /*if (!TextUtils.isEmpty(object.getConstellation())) {
            labelData.add(object.getConstellation());
            sb.append(object.get)
        }
        if (!TextUtils.isEmpty(object.getAscription())) {
            labelData.add(object.getAscription());
        }
        if (!TextUtils.isEmpty(object.getHeight())) {
            String height = Utils.spitHeight(object.getHeight(), 0);
            String w = Utils.spitHeight(object.getHeight(), 1);
            labelData.add(height + "  " + w);
        }*/
        if (!TextUtils.isEmpty(object.getVoiceInfo())) {
            linearVoice.setVisibility(View.VISIBLE);
        } else {
            linearVoice.setVisibility(View.GONE);
        }
        //labelData.add(Utils.getAge(object.getBirthday()) + "岁");
        //largeLabe2.setLabels(labelData);
        tvNikeName.setText(object.getNickName());
        tvIntro.setText(object.getAutograph());
        if (!TextUtils.isEmpty(object.getvType())) {
            if (object.getvType().equals("0")) {// 会员等级 0非会员 1月会员 2年会员
                imageVip.setVisibility(View.GONE);
            } else if (object.getvType().equals("1")) {
                imageVip.setVisibility(View.VISIBLE);
                imageVip.setImageResource(R.mipmap.vip_month);
            } else if (object.getvType().equals("2")) {
                imageVip.setVisibility(View.VISIBLE);
                imageVip.setImageResource(R.mipmap.vip_year);
            }
        }
        if (object.getGender() == 1) {//性别  1男2女
            linearBackAge.setBackgroundResource(R.mipmap.sex_blue);
            imageSex.setImageResource(R.mipmap.boy);
            sbData.append("性别：男" + "\n");
        } else {
            linearBackAge.setBackgroundResource(R.mipmap.sex_red);
            imageSex.setImageResource(R.mipmap.girl);
            sbData.append("性别：女" + "\n");
        }
        if (!TextUtils.isEmpty(object.getBirthday())) {
            tvAge.setText(Utils.getAge(object.getBirthday()));
            sbData.append("年龄：" + tvAge.getText().toString() + "\n");
        }
        sbData.append("隐隐ID:" + object.getNumber() + "\n");
        // tvUserId.setText("ID:" + object.getNumber());
        if (object.getType() == 2) {////1普通用户2主播
            imageIsAnchor.setVisibility(View.VISIBLE);
           // tvAnchorText.setVisibility(View.VISIBLE);
           // Log.i(TAG, "setHeardData: --getExclusiveUrl----"+object.getExclusiveUrl());
            GlideLoadUtils.getInstance().glideLoad(context, OssConfig.OSS_HTTP + object.getExclusiveUrl(),
                    imageIsAnchor);
            if (!TextUtils.isEmpty(object.getLabourName())) {
                tvAnchorText.setText(object.getLabourName());
            }
        } else {
            imageIsAnchor.setVisibility(View.GONE);
            tvAnchorText.setVisibility(View.GONE);
        }
        if(mySeleInfo.getIsAttestation() == 1){
            imageIsReal.setVisibility(View.VISIBLE);
        }else {
            imageIsReal.setVisibility(View.GONE);
        }
        //语音介绍
        if (!TextUtils.isEmpty(object.getVoiceInfo()) && object.getDuration() != 0) {
            //voiceTime.setText(object.getDuration() + "”");
        } else {
            linearVoice.setVisibility(View.GONE);
        }
        /*if (object.getMark() == 1) {
            if (object.getStatus() == 1) {//1空闲 0离线
                tvLineState.setText("·空闲");
                tvLineState.setTextColor(context.getResources().getColor(R.color.colorff55dc9d));
            } else if (object.getStatus() == 3) {
                tvLineState.setText("·忙碌");
                tvLineState.setTextColor(context.getResources().getColor(R.color.colorff6600));
            } else {
                tvLineState.setText("·离线");
                tvLineState.setTextColor(context.getResources().getColor(R.color.colorAAAAAA));
            }
        } else {
            tvLineState.setText("·离线");
            tvLineState.setTextColor(context.getResources().getColor(R.color.colorAAAAAA));
        }*/

    }

    /**
     * @return
     * @method
     * @description 播放语音
     * @date: 2018/9/28 18:57
     * @author: ljp
     */
    private void player(String path) throws FileNotFoundException {
        // Log.i(TAG, "player: ---voicePath--"+voicePath);
        // Log.i(TAG, "player: ---audioFilePath--"+audioFilePath);
        if (TextUtils.isEmpty(path)) {
            return;
        }
        if (mediaUtil == null) {
            mediaUtil = MediaUtil.getInstance();
            mediaUtil.play(new FileInputStream(path));
            // frameAnimatio.start();
        } else {
            if (mediaUtil.setPlayer()) {
                mediaUtil.stop();
                // frameAnimatio.stop();
                //imageVoice.setBackgroundResource(0);
                imageVoice.setImageResource(R.mipmap.person_voice_pause);
            } else {
                mediaUtil.play(new FileInputStream(path));
                // imageVoice.setImageResource(0);
                imageVoice.setImageResource(R.mipmap.person_voice_open);
                //  frameAnimatio = (AnimationDrawable) imageVoice.getBackground();
                //  frameAnimatio.start();
            }
        }
        mediaUtil.setEventListener(new MediaUtil.EventListener() {
            @Override
            public void onStop() {
                // frameAnimatio.stop();
                // imageVoice.setBackgroundResource(0);
                imageVoice.setImageResource(R.mipmap.person_voice_pause);
                // imageVoice.setImageResource(R.mipmap.set_voice_play3);
            }
        });
    }

    /**
     * @return
     * @method
     * @description 启动线程池下载语音介绍信息
     * @date: 2018/10/16 14:30
     * @author: ljp
     */
    private void setThread(String voiceName1) {
        ThreadManager.getThreadPool().execute(runnable = new Runnable() {
            @Override
            public void run() {
                OssClient.getInstance().init(context).fileDownload(voiceName1, new OssClient.OnDownloadFile() {
                    @Override
                    public void onDownFileSuccess(InputStream inputStream) {
                        String voiceName = Utils.getVoiceName(voiceName1);
                        //Log.i(TAG, "onDownFileSuccess: ---------"+voiceName);
                        String path = ConstantSet.VOICEINTR;
                        voicePath = ConstantSet.VOICEINTR + ConstantSet.VOICEINTR_PATH + voiceName;
                        try {
                            OssConfig.writeToLocal(path, inputStream, voiceName);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onDownFileProgress(String progress) {
                        //Log.i(TAG, "onDownFileProgress: ----------"+progress);
                    }
                });
            }
        });
    }

    /**
     * @return
     * @method
     * @description 请求礼物信息
     * @date: 2018/10/26 17:33
     * @author: ljp
     */
    private void setHomeGif() {
        PersonDataService.personHomeGifAll(token, deviceInfo, anchorId, page + "").subscribe(gifBean -> {
            Log.i(TAG, "setHomeHeard: ----" + gifBean.toString());
            if (gifBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                if (gifBean.getPage().getList() != null) {
                    gifBeans.addAll(gifBean.getPage().getList());
                    gifAdapter.notifyDataSetChanged();
                } else {
                    linearMyGif.setVisibility(View.GONE);
                    viewGift.setVisibility(View.GONE);
                }
            } else if (gifBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(gifBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "setHomeGif: ----------" + throwable.toString());
            toast_MakeText(getResources().getString(R.string.net_error));

        });
    }

    /**
     * @return
     * @method
     * @description 请求个人相册信息
     * @date: 2018/10/26 17:33
     * @author: ljp
     */
    private void setHomePhoto() {
        PersonDataService.showPersonPhotos(token, deviceInfo, anchorId).subscribe(photoAlbumBean -> {
            //Log.i(TAG, "setHomePhoto: ----" + photoAlbumBean.toString());
            if (photoAlbumBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                if (photoAlbumBean.getPage().getList() != null && photoAlbumBean.getPage().getList().size() != 0) {
                    // String[] strings = Utils.spitPictureUrl(photoAlbumBean.getPage().getList().get(0).getAlbumUrl());
                    listImages.addAll(photoAlbumBean.getPage().getList());
                    pictureAdapter.notifyDataSetChanged();
                } else {
                    linearMyPhoto.setVisibility(View.GONE);
                    viewPhoto.setVisibility(View.GONE);
                }
            } else if (photoAlbumBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(photoAlbumBean.getMsg());
            }
        }, throwable -> {

        });
    }

    /**
     * @return
     * @method
     * @description 请求粉丝关注点赞访客
     * @date: 2018/10/26 17:33
     * @author: ljp
     */
    private void setHomeState() {
        PersonDataService.showPersonState(token, deviceInfo, id, anchorId).subscribe(charmBean -> {
            Log.i(TAG, "setHomeState: ----" + charmBean.getObject().toString());
            if (charmBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                charmBeanObject = charmBean.getObject();
                setHomeFans(charmBean.getObject());
            } else if (charmBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(charmBean.getMsg());
            }
        }, throwable -> {
        });
    }

    /**
     * @return
     * @method
     * @description 页面粉丝，魅力值数据
     * @date: 2018/10/29 11:01
     * @author: ljp
     */
    private void setHomeFans(CharmBean.ObjectBean object) {
        //判断是否关注此用户
        if (object.getState() == 1) {//1 未关注 2已经关注 3互相关注
            tvAttention.setText("关注");
            imageAttention.setImageResource(R.mipmap.person_flow);
            linearAttention.setBackgroundResource(R.drawable.btn_layout_red);
        } else if (object.getState() == 2) {
            imageAttention.setImageResource(0);
            tvAttention.setText("已关注");
            linearAttention.setBackgroundResource(R.drawable.btn_layout_red);
        } else if (object.getState() == 3) {
            imageAttention.setImageResource(0);
            tvAttention.setText("互相关注");
            linearAttention.setBackgroundResource(R.drawable.login_btn_d5d5d5);
        }
        tvFans.setText(object.getFans());
        tvConcern.setText(object.getFollow());
        AssetManager mgr = getAssets();
        Typeface tf = Typeface.createFromAsset(mgr, "fonts/alternate_bold.ttf");
        tvFans.setTypeface(tf);
        tvConcern.setTypeface(tf);
        sbData.append("魅力值：" + object.getTotalIncome() + "\n");
        sbData.append("土豪值：" + object.getWealth() + "\n");
        tvData.setText(sbData.toString());
    }

    /**
     * @return
     * @method
     * @description 请求语聊数据
     * @date: 2018/10/26 17:33
     * @author: ljp
     */
    private void showPersonVoice() {
        PersonDataService.showPersonVoice(token, deviceInfo, anchorId).subscribe(voiceAppraiseBean -> {
            //Log.i(TAG, "showPersonVoice: ----------"+voiceAppraiseBean.getObject().toString());
            if (voiceAppraiseBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                setPersonVoice(voiceAppraiseBean.getObject());
            } else if (voiceAppraiseBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(voiceAppraiseBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "showPersonVoice: -----" + throwable.toString());
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }

    /**
     * @return
     * @method
     * @description 他的语聊数据设置
     * @date: 2018/10/29 14:17
     * @author: ljp
     */
    private void setPersonVoice(VoiceAppraiseBean.ObjectBean object) {
        if (object.getList() != null) {
            for (int i = 0; i < object.getList().size(); i++) {
                VoiceAppraiseBean.ObjectBean.ListBean listBean = object.getList().get(i);
                if (listBean != null && listBean.getTagName() != null) {
                    labeVoice.add(listBean.getTagName());
                }
            }
            largeLabel.setLabels(labeVoice);
            largeLabel.setLabelTextColorRandom(Utils.LABELCOLOR);
        } else {
            linearLabel.setVisibility(View.GONE);
            viewLabel.setVisibility(View.GONE);
        }

        //  tvCallRate.setText("通话率" + object.getProbability());
        //  tvCallNumber.setText("通话数" + object.getCount());
        // ratingBar.setStar(object.getStar(), false, activity);
        // tvScores.setText(object.getStar() + ".0分");

    }

    /**
     * @return
     * @method
     * @description 请求动态数据
     * @date: 2018/10/26 17:33
     * @author: ljp
     */
    private void showPersonPosts() {
        MeInfoService.dynamicPage(token, deviceInfo, id, anchorId, page + "", "2").subscribe(postBean -> {
            // Log.i(TAG, "setHomeHeard: ----" + postBean.getPage().getList().size());
            if (postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                if (postBean.getPage().getList() != null) {
                    postLists.addAll(postBean.getPage().getList());
                    communityAdapter.notifyDataSetChanged();
                    setThreadPost(postBean.getPage().getList());
                } else {
                    linearDynamicState.setVisibility(View.GONE);
                }
            } else if (postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(postBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "showPersonPosts: ----" + throwable.toString());

        });
    }

    /**
     * 标题栏/导航栏icon 颜色改变
     *
     * @param color
     */
    private void iconColorFilter(int color) {
        PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP);
        imageBack.setColorFilter(colorFilter);
        imageMoreTr.setColorFilter(colorFilter);
        imageShareTr.setColorFilter(colorFilter);
        imageAdd.setColorFilter(colorFilter);
    }

    @OnClick({R.id.image_back, R.id.image_share_tr, R.id.image_more_tr,
            R.id.linear_my_photo, R.id.linear_my_gif, R.id.linear_dynamic_state, R.id.linear_gif,
            R.id.linear_accost, R.id.linear_voice, R.id.linear_call, R.id.linear_add_friends})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.image_share_tr:
                break;
            case R.id.linear_add_friends://添加隐友
                addFriends();
                break;
            case R.id.image_more_tr://更多
                showPopu(view);
                break;
            case R.id.linear_my_photo://我的相册
                if (mySeleInfo.getvType().equals("0")) {
                    toast_MakeText(getResources().getString(R.string.vip_text));
                }else {
                    Intent intent1 = new Intent(activity, PhotoAlbumActivity.class);
                    intent1.putExtra("anchorId", anchorId);
                    startActivity(intent1);
                }
                break;
            case R.id.linear_my_gif://ta的礼物
                intent = new Intent(activity, GifListActivity.class);
                intent.putExtra("anchorId", anchorId);
                startActivity(intent);
                break;
            case R.id.linear_dynamic_state://我的动态
                if (mySeleInfo.getvType().equals("0")) {
                    toast_MakeText(getResources().getString(R.string.vip_text));
                }else {
                    intent = new Intent(activity, OtherDynamicPageActivity.class);
                    intent.putExtra("anchorId", anchorId);
                    startActivity(intent);
                }
                break;
            case R.id.linear_accost://搭讪，先请求送搭讪礼物，然后跳转聊天页面
                // sendGiftAccost();
                if (objectBean != null) {
                    // 会员类型  0非会员 1月会员 2年会员   //1普通用户2主播
                    /*if(mySeleInfo.getvType().equals("0") && mySeleInfo.getType() == 1 ){
                        myDialog.setGone().setMsg(getResources().getString(R.string.accost)).
                                // setNegativeButton("再想想",R.color.colorAccent,null).
                                        setPositiveButton("确定", R.color.colorAccent, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        IMChatActivity.navToChat(context, anchorId, objectBean.getNickName(), String.valueOf(objectBean.getType()), "accost");
                                    }
                                }).show();
                        return;
                    }
                    if(mySeleInfo.getType() == 1 && mySeleInfo.getvType().equals("0")){
                        myDialog.setGone().setMsg(getResources().getString(R.string.accost)).
                                // setNegativeButton("再想想",R.color.colorAccent,null).
                                        setPositiveButton("确定", R.color.colorAccent, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        IMChatActivity.navToChat(context, anchorId, objectBean.getNickName(), String.valueOf(objectBean.getType()), "accost");
                                    }
                                }).show();
                        return;
                    }*/
                    if (mySeleInfo.getvType().equals("0") /*&& mySeleInfo.getType() == 1*/) {
                        myDialog.setGone().setMsg(getResources().getString(R.string.accost)).
                                // setNegativeButton("再想想",R.color.colorAccent,null).
                                        setPositiveButton("确定", R.color.colorAccent, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        IMChatActivity.navToChat(context, anchorId, objectBean.getNickName(), String.valueOf(objectBean.getType()), "accost");
                                    }
                                }).show();
                    } else {
                        IMChatActivity.navToChat(context, anchorId, objectBean.getNickName(), String.valueOf(objectBean.getType()), "accost");
                    }
                }
                break;
            case R.id.linear_gif://我的礼物
                //弹出礼物页面
                setPopuGift();
                break;
            case R.id.linear_voice://播放语音
                //  imageVoice.setImageResource(0);
                imageVoice.setImageResource(R.mipmap.person_voice_open);
                frameAnimatio = (AnimationDrawable) imageVoice.getBackground();
                try {
                    if (voicePath != null) {
                        player(voicePath);
                    } else {
                        setThread(objectBean.getVoiceInfo());
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.linear_call://语音通话页面
                if (Build.VERSION.SDK_INT < 23) {
                    if (CheckAudioPermission.isHasPermission(context)) {
                        judeType();
                    } else {
                        ActivityCompat.requestPermissions(activity, new String[]{
                                Manifest.permission.RECORD_AUDIO}, 1);
                    }
                } else {
                    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(activity, new String[]{
                                Manifest.permission.RECORD_AUDIO}, 1);
                    } else {
                        judeType();
                    }
                }
                break;
        }
    }

    /**
     * @return
     * @method
     * @description 添加好友
     * @date: 2019/1/22 16:25
     * @author: ljp
     */
    private void addFriends() {
        MeInfoService.addFriends(token, deviceInfo, mySeleInfo.getId(), anchorId).subscribe(result -> {
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                toast_MakeText("好友请求已发送，等待对方同意");
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });


    }

    /**
     * @return
     * @method
     * @description 搭讪送礼物
     * @date: 2018/12/1 10:43
     * @author: ljp
     */
    private void sendGiftAccost() {
        MeInfoService.sendGiftChat(mySeleInfo.getId(), token, deviceInfo, anchorId, "", "", "6", "1").subscribe(result -> {
            Log.i(TAG, "onReceive: ---------" + result);
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                toast_MakeText("搭讪成功！");
                IMChatActivity.navToChat(context, anchorId, objectBean.getNickName(), String.valueOf(objectBean.getType()), "accost");
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_GOLD) {
                toast_MakeText(result.getMsg());
            } else {
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "onReceive: ----" + throwable.toString());
        });

    }

    /**
     * @return
     * @method
     * @description 是主播还是用户判断
     * @date: 2018/11/26 17:53
     * @author: ljp
     */
    private void judeType() {
        //首先判断自己是否是用户
        if (mySeleInfo.getType() == 1) {
            //然后判断对方是否是用户
            if (objectBean.getType() == 1) {
                //弹出金币设置页面
                showGoldPopu();
            } else {
                VoiceChatJude();
            }
        } else {
            VoiceChatJude();
        }
    }

    /**
     * @return
     * @method
     * @description 普通用户金币设置
     * @date: 2018/11/26 17:55
     * @author: ljp
     */
    private void showGoldPopu() {
        View view = View.inflate(context, R.layout.popu_gold_layout, null);
        PopUtils.showPopupWindow(activity, view, false);
        ImageView imageClose = view.findViewById(R.id.image_close);
        TextView textView = view.findViewById(R.id.tv_voice_chat);
        TextView textViewConent = view.findViewById(R.id.tv_conent);
        textViewConent.setText(getResources().getString(R.string.voice_chat_price));
        textView.setText("通话");
        imageClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PopUtils.isPopShowing()) {
                    PopUtils.hidePopupWindow();
                }
            }
        });
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               /* if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(activity, new String[]{
                            Manifest.permission.RECORD_AUDIO}, 1);
                } else {*/
                VoiceChatJude();
                //  }
                PopUtils.hidePopupWindow();
            }
        });
    }

    /**
     * ⑨重写onRequestPermissionsResult方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            judeType();
        } else {
            Toast.makeText(activity, "用户拒绝了权限,请先去设置中打开录音权限", Toast.LENGTH_SHORT).show();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * @return
     * @method
     * @description 向对方发起语音通话请求
     * @date: 2018/11/21 12:06
     * @author: ljp
     */
    private void VoiceChatJude() {
        MeInfoService.voiceChatJude(anchorId, token = SPUtils.getEditoString(SPUtils.SP_TOKEN), PhoneUtils.getDeviceInfo(context), mySeleInfo.getId()).subscribe(voiceChatBean -> {
            Log.i(TAG, "VoiceChatJude: ---------" + voiceChatBean.getCode());
            Log.i(TAG, "VoiceChatJude: ---------" + voiceChatBean.getMsg());
            //Log.i(TAG, "VoiceChatJude: ---------"+ voiceChatBean.getObject().toString());
            if (voiceChatBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_LINE) {//自己下线，重连长链接
                WsManager.getInstance(context).reconnect(mySeleInfo.getId());
                toast_MakeText("请重试！");
            } else if (voiceChatBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_FAIL) {
                toast_MakeText(voiceChatBean.getMsg());
            } else if (voiceChatBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {//用户在线，可以通话
                Intent intent = new Intent(activity, InviteVoiceChatActivity.class);
                Bundle bundle = new Bundle();
               /* bundle.putString("type", "1");
                bundle.putString("flag", "0");*/
                bundle.putInt("roomId", voiceChatBean.getObject().getRoomId());
                bundle.putParcelable("voiceChat", voiceChatBean.getMap().getCalledUser());
                bundle.putParcelable("voiceChatCalling", voiceChatBean.getMap().getCallingUser());
                intent.putExtra("type", "1");
                intent.putExtra("flag", "0");
                intent.putExtra("bundle", bundle);
                activity.startActivity(intent);
            } else if (voiceChatBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(voiceChatBean.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            Log.i(TAG, "VoiceChatJude: ----------" + throwable.toString());
        });

    }

    /**
     * @method
     * @description 弹出打赏页面
     * @date: 2018/11/19 19:51
     * @author: ljp
     * @return
     */
    ViewPager viewPagerGif;
    TextView tvGoldSum;
    LinearLayout linearRecharge;
    TextView tvSendGift;
    ImageView imageClose;
    CirclePageIndicator llPointGroup;
    public static int gridColumn = 4;//grid的列数
    public static int gridNum = 8;//grid的一页总数
    private ViewPagerAdapter mAdapter;
    private List<GridView> gridViews;
    ListBean giftBean;//选中的礼物

    private void setPopuGift() {
        View view = View.inflate(context, R.layout.popu_gift_fragment, null);
        tvSendGift = view.findViewById(R.id.tv_send);
        linearRecharge = view.findViewById(R.id.linear_recharge);
        tvGoldSum = view.findViewById(R.id.tv_gold_sum);
        viewPagerGif = view.findViewById(R.id.view_pager_gif);
        llPointGroup = view.findViewById(R.id.ll_point_group);
        imageClose = view.findViewById(R.id.image_close);
        initPopuView();
        initDatas();
        initHttpGetGold();
        PopUtils.initPopupWindow(activity, view, false);

        PopUtils.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = activity.getWindow().getAttributes();
                params.alpha = 1.0f;//设置为不透明，即恢复原来的界面
                activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                activity.getWindow().setAttributes(params);
                //giftBean = null;
            }
        });
        imageClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopUtils.hidePopupWindow();
            }
        });
        linearRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopUtils.hidePopupWindow();
                Uri uri = Uri.parse(HTTPAPI.URL_RECHARGE + "id=" + mySeleInfo.getNumber());
                Log.i(TAG, "onClick: --------" + uri.toString());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        tvSendGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: -------------------");
                if (giftBean != null) {
                    MeInfoService.sendGift(id, token, deviceInfo, anchorId, giftBean.getId(),
                            giftBean.getGold() + "", PersonDataService.GIF_TYPE.GIF_GET, "", "1", "").subscribe(result -> {
                        Log.i(TAG, "onClick: ------" + result.toString());
                        if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                            toast_MakeText("送礼成功！");
                            gifBeans.clear();
                            page = 1;
                            setHomeGif();
                            PopUtils.hidePopupWindow();
                            try {
                                if (!TextUtils.isEmpty(giftBean.getAnimationUrl())) {
                                    loadAnimation(new URL(OssConfig.OSS_HTTP + giftBean.getAnimationUrl()));
                                }
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            }
                        } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_GOLD) {
                            toast_MakeText("金币余额不足，请充值！");
                        } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_FAIL) {
                            toast_MakeText("送礼失败，请重试！");
                        } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                            Utils.setToken(context);
                        } else {
                            toast_MakeText(result.getMsg());
                        }
                    }, throwable -> {
                        Log.i(TAG, "onClick: -----" + throwable.toString());
                    });
                } else {
                    toast_MakeText("请选择礼物");
                }

            }
        });
    }

    private void loadAnimation(URL url) {
        SVGAParser parser = new SVGAParser(this);
        resetDownloader(parser);
        parser.parse(url, new SVGAParser.ParseCompletion() {
            @Override
            public void onComplete(@NotNull SVGAVideoEntity videoItem) {
                SVGADrawable drawable = new SVGADrawable(videoItem, requestDynamicItemWithSpannableText());
                svgImage.setVisibility(View.VISIBLE);
                linearChat.setVisibility(View.GONE);
                svgImage.setImageDrawable(drawable);
                svgImage.setLoops(1);
                svgImage.startAnimation();
            }

            @Override
            public void onError() {
            }
        });
        svgImage.setCallback(new SVGACallback() {
            @Override
            public void onPause() {
            }

            @Override
            public void onFinished() {
                svgImage.setVisibility(View.GONE);
                linearChat.setVisibility(View.VISIBLE);
            }

            @Override
            public void onRepeat() {
            }

            @Override
            public void onStep(int frame, double percentage) {
            }
        });
    }

    /**
     * 你可以设置富文本到 ImageKey 相关的元素上
     * 富文本是会自动换行的，不要设置过长的文本
     *
     * @return
     */
    private SVGADynamicEntity requestDynamicItemWithSpannableText() {
        SVGADynamicEntity dynamicEntity = new SVGADynamicEntity();
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("Pony 送了一打风油精给主播");
        spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        TextPaint textPaint = new TextPaint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(28);
        dynamicEntity.setDynamicText(new StaticLayout(
                spannableStringBuilder,
                0,
                spannableStringBuilder.length(),
                textPaint,
                0,
                Layout.Alignment.ALIGN_CENTER,
                1.0f,
                0.0f,
                false
        ), "banner");
        dynamicEntity.setDynamicDrawer(new Function2<Canvas, Integer, Boolean>() {
            @Override
            public Boolean invoke(Canvas canvas, Integer frameIndex) {
                Paint aPaint = new Paint();
                aPaint.setColor(Color.WHITE);
                canvas.drawCircle(50, 54, frameIndex % 5, aPaint);
                return false;
            }
        }, "banner");
        return dynamicEntity;
    }

    /**
     * 设置下载器，这是一个可选的配置项。
     *
     * @param parser
     */
    private void resetDownloader(SVGAParser parser) {
        parser.setFileDownloader(new SVGAParser.FileDownloader() {
            @Override
            public void resume(final URL url, final Function1<? super InputStream, Unit> complete, final Function1<? super Exception, Unit> failure) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder().url(url).get().build();
                        try {
                            Response response = client.newCall(request).execute();
                            complete.invoke(response.body().byteStream());
                        } catch (IOException e) {
                            e.printStackTrace();
                            failure.invoke(e);
                        }
                    }
                }).start();
            }
        });
    }

    /**
     * @return
     * @method
     * @description 余额请求
     * @date: 2018/11/7 14:39
     * @author: ljp
     */
    private void initHttpGetGold() {
        MeInfoService.goldDiamond(id, token, deviceInfo).subscribe(goldBean -> {
            //Log.i(TAG, "initHttp: -------"+goldBean.getObject().toString());
            if (goldBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                tvGoldSum.setText(goldBean.getObject().getGold() + "");
            } else if (goldBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(goldBean.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "initHttp: -----" + throwable.toString());
        });

    }

    /**
     * @return
     * @method
     * @description 数据控件实例化
     * @date: 2018/11/13 10:07
     * @author: ljp
     */
    List<ListBean> listBeans;

    private void initPopuView() {
        gridViews = new ArrayList<>();
        listBeans = new ArrayList<>();
        listBeans.addAll(RealmUtils.getInstance()
                .getRealm()
                .where(ListBean.class)
                .findAll());
        Log.i(TAG, "initPopuView: ----" + listBeans.size());
        mAdapter = new ViewPagerAdapter();
        viewPagerGif.setAdapter(mAdapter);
        llPointGroup.setVisibility(View.VISIBLE);
        llPointGroup.setViewPager(viewPagerGif);

    }

    /**
     * @return
     * @method
     * @description 礼物数据实例化
     * @date: 2018/11/20 11:23
     * @author: ljp
     */
    private void initDatas() {
        //计算viewpager一共显示几页
        int pageSize = listBeans.size() % gridNum == 0
                ? listBeans.size() / gridNum
                : listBeans.size() / gridNum + 1;
        for (int i = 0; i < pageSize; i++) {
            GridView gridView = new GridView(activity);
            MsgGifGridViewAdapter adapter = new MsgGifGridViewAdapter(listBeans, i);
            gridView.setNumColumns(gridColumn);
            gridView.setHorizontalSpacing(5);
            gridView.setVerticalSpacing(10);
            gridView.setAdapter(adapter);
            int finalI = i;
            adapter.setItemClick(new MsgGifGridViewAdapter.ItemClick() {
                @Override
                public void setItemClick(int position) {
                }
            });
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    adapter.setCheckd(true, position);
                    adapter.notifyDataSetChanged();
                    giftBean = adapter.getItem(position);
                    //toast_MakeText(adapter.getItem(position)+"");
                }
            });
            gridViews.add(gridView);
        }
        mAdapter.add(gridViews);
    }

}
